/*
 * Copyright 2019 WeBank
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.webank.wedatasphere.qualitis.rule.dao.impl;

import com.webank.wedatasphere.qualitis.rule.dao.UserRuleTemplateDao;
import com.webank.wedatasphere.qualitis.rule.dao.repository.UserRuleTemplateRepository;
import com.webank.wedatasphere.qualitis.rule.entity.Template;
import com.webank.wedatasphere.qualitis.rule.entity.TemplateUser;
import com.webank.wedatasphere.qualitis.rule.dao.UserRuleTemplateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author howeye
 */
@Repository
public class UserRuleTemplateDaoImpl implements UserRuleTemplateDao {

    @Autowired
    private UserRuleTemplateRepository userRuleTemplateRepository;

    @Override
    public List<Template> findByUserId(Long userId, int page, int size) {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page, size, sort);
        return userRuleTemplateRepository.findByUserId(userId, pageable).getContent().stream().map(TemplateUser::getTemplate).collect(Collectors.toList());
    }

    @Override
    public Long countByUserId(Long userId) {
        return userRuleTemplateRepository.countByUserId(userId);
    }
}
